package com.spider.gp.schedule;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spider.gp.controller.SpriderController;
import com.spider.gp.controller.SuanfaController;
import com.spider.gp.controller.TongJiController;
import com.spider.gp.dao.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * description:
 *
 * @author clare
 * @date 2022/06/06 09:58
 **/
@EnableScheduling
@Component
@Slf4j
public class gpSchedule {

    @Autowired
    private SpriderController spriderController;

    @Autowired
    private TongJiController tongJiController;
    @Autowired
    private SuanfaController suanfaController;
    @Autowired
    private GpGzDao gpGzDao;
    @Autowired
    private GpInfoDao gpInfoDao;
    @Autowired
    private LowHighDao lowHighDao;
    @Autowired
    private ZhiShuDao zhiShuDao;
    @Autowired
    private GpDetailDao gpDetailDao;
    @Autowired
    private LowHighTjDetailDao lowHighTjDetailDao;

    @PostConstruct
    public void testAll() {
        System.out.println("...。");
    }

    /**
     * 最低最高点预测法
     */
    @Scheduled(cron = "0 20 15 ? * MON-FRI")
//    @PostConstruct
    public void lowHighTjAll() {
        //更新每日股票价格
        gpDetailAll();
        //更新 最高最低点
        lowHighAll();
//        //第一层统计： 根据天统计该天的最低点，最低点gp群
        lowHighTj();
//        //第二层统计： 追踪跟上证或者深证共振的股票 目前是所有的
        tongJiController.lowTjDetail();
        //实时预测
        tongJiController.lowTjDetailSS();
    }

    /**
     * 处理除权问题 --每周五下午更新
     */
    @Scheduled(cron = "0 20 21 ? * FRI")
//    @PostConstruct
    public void lowHighTjAllNew() {
        //清除重新更新
        gpDetailDao.delete(new LambdaQueryWrapper<>());
        //更新每日股票价格
        gpDetailAll();
        //全部更新
        lowHighDao.delete(new LambdaQueryWrapper<>());
        //更新 最高最低点
        lowHighAll();
        //第一层统计： 根据天统计该天的最低点，最低点gp群
        lowHighTjAllALL();

        //重新计算最近5条
        LambdaQueryWrapper<LowHighTjDetail> wrapperDetail = new LambdaQueryWrapper<>();
        wrapperDetail.orderByDesc(LowHighTjDetail::getReportTime).last(" limit 10 ");
        List<LowHighTjDetail> lowHighTjDetails = lowHighTjDetailDao.selectList(wrapperDetail);
        LowHighTjDetail lowHighTjDetail = lowHighTjDetails.get(4);

        LambdaQueryWrapper<LowHighTjDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.ge(LowHighTjDetail::getReportTime, lowHighTjDetail.getReportTime());
        lowHighTjDetailDao.delete(wrapper);

        tongJiController.lowTjDetail();
        tongJiController.lowTjDetailSS();
    }

    /**
     * 均线
     */
    @Scheduled(cron = "0 31 15 ? * MON-FRI")  //
    public void pjpj() {
        //今日均线计算
        suanfaController.pjpjToday();
        //均线平均
        suanfaController.pjpjjzToday(3);
        suanfaController.pjpjjzToday(8);
    }


    @Scheduled(cron = "0 35 9,11,13,15 ? * MON-FRI")  //
//    @PostConstruct
    public void zrzt() {
        //指数  這裏只能跑當日的
        try {
            spriderController.zhiShu();
        } catch (Exception e) {
            System.out.println("指数爬虫失败," + e.getMessage());
        }

        LambdaQueryWrapper<ZhiShu> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(ZhiShu::getReportTime).last(" limit 2");
        List<ZhiShu> zhiShus = zhiShuDao.selectList(wrapper);
        ZhiShu zhiShu = zhiShus.get(0);
        ZhiShu zhiShu01 = zhiShus.get(1);
        if (zhiShu.getSzczCjl().equals(zhiShu01.getSzczCjl()) &&
                zhiShu.getSzczJia().equals(zhiShu01.getSzczJia()) &&
                zhiShu.getSzzsZf().equals(zhiShu01.getSzzsZf()) &&
                zhiShu.getSzzsJia().equals(zhiShu01.getSzzsJia())) {

            LambdaQueryWrapper<ZhiShu> wrapperdelete = new LambdaQueryWrapper<>();
            wrapperdelete.eq(ZhiShu::getReportTime, zhiShu.getReportTime());
            zhiShuDao.delete(wrapperdelete);
            return;
        }


        //行业 這裏只能跑當日的
        try {
            spriderController.hangYe();
        } catch (Exception e) {
            System.out.println("行业爬虫失败," + e.getMessage());
        }







    }

    /**
     * 涨跌停统计
     *
     * @throws IOException
     * @throws InterruptedException
     */
    @Scheduled(cron = "0 45 9,11,16 ? * MON-FRI")  //
    public void zdt() throws IOException, InterruptedException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String reportTime = formatter.format(new Date());
//        String reportTime ="2023-04-14";
        //妖股统计
        try {
            tongJiController.yaogu(reportTime);
        } catch (Exception e) {
            System.out.println("妖股统计失败," + e.getMessage());
        }
//        涨跌停比
        try {
            tongJiController.zdtb(reportTime);
        } catch (Exception e) {
            System.out.println("涨跌停比统计失败," + e.getMessage());
        }
        //成交量统计
        try {
            tongJiController.cJList(reportTime);
        } catch (Exception e) {
            System.out.println("成交量统计统计失败," + e.getMessage());
        }
        //连板
        try {
            tongJiController.lianbanBK(reportTime);
        } catch (Exception e) {
            System.out.println("连板统计统计失败," + e.getMessage());
        }


    }

    /**
     * 跌停池
     *
     * @throws IOException
     * @throws InterruptedException
     */
    @Scheduled(cron = "0 35 9,10,11,13,14,15 ? * MON-FRI")  //
    public void dtc() throws IOException, InterruptedException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String reportTime = formatter.format(new Date());
//        String reportTime ="20230414";
        //跌停池
        try {
            spriderController.dtc(reportTime);
        } catch (Exception e) {
            System.out.println("跌停池爬虫失败," + e.getMessage());
        }
        //连板池
        try {
            spriderController.lianBan(reportTime);
        } catch (Exception e) {
            System.out.println("连板池爬虫失败," + e.getMessage());
        }
        //昨日指数
        try {
            spriderController.zrzt(reportTime);
        } catch (Exception e) {
            System.out.println("昨日指数爬虫失败，" + e.getMessage());
        }


    }


    @Scheduled(cron = "0 15,30 17 ? * MON-FRI")  //
    public void longHuBang() throws IOException, InterruptedException {
        spriderController.longHuBang();
    }


    /**
     * 行业板块以及股票更新
     *
     * @throws IOException
     * @throws InterruptedException
     */
    @Scheduled(cron = "0 0 0 1 * ?")  //
    public void hy() throws IOException, InterruptedException {
        spriderController.hyAll();
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //BK0597   BK0853 BK0900 BK0854 BK0954 BK0906 BK0908 BK0910
        spriderController.gpHyAll("");
    }


    @Scheduled(cron = "0 0 0 1 1/2 ?")  //每三个月更新一次
    public void gpInfo() {
        spriderController.gpInfo();
    }


    /**
     * 统计
     */
    public void lowHighTj() {
        LambdaQueryWrapper<ZhiShu> wrapperZS = new LambdaQueryWrapper<>();
        wrapperZS.orderByDesc(ZhiShu::getReportTime).last("  limit 10,5 "); //允许5天的差值
        List<ZhiShu> zhiShus = zhiShuDao.selectList(wrapperZS);
//        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//        String reportTime = formatter.format(new Date());
        tongJiController.lhtjAll(zhiShus);
    }

    public void lowHighTjAllALL() {
        LambdaQueryWrapper<ZhiShu> wrapperZS = new LambdaQueryWrapper<>();
        wrapperZS.gt(ZhiShu::getReportTime, "2023-01-01");
//        wrapperZS.orderByDesc(ZhiShu::getReportTime).last("  limit 10,5 "); //允许5天的差值
        List<ZhiShu> zhiShus = zhiShuDao.selectList(wrapperZS);
//        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//        String reportTime = formatter.format(new Date());
        tongJiController.lhtjAll(zhiShus);
    }


    /**
     * 股票详情，每天的收盘后更新 -数据来源网站
     */

    public void gpDetailAll() {
        spriderController.gpDetail("000001", "1");
        spriderController.gpDetail("399001", "0");
        List<GpInfo> gpInfos = gpInfoDao.selectList(new LambdaQueryWrapper<>());
        gpInfos.parallelStream().filter(a -> !a.getShortName().contains("ST") && !a.getShortName().contains("退市") && !a.getZsz().contains("-")
                && !a.getCode().startsWith("8")).forEach(a -> {
            spriderController.gpDetail(a.getCode(), a.getSecurityCodeType());
        });
    }


    /**
     * 求最低最高点 -全量 -数据来源网站
     */
    public void lowHighAll() {
        // 先更新
        spriderController.hignLow("000001", "1");
        spriderController.hignLow("399001", "0");

        List<GpInfo> gpInfos = gpInfoDao.selectList(new LambdaQueryWrapper<>());
        gpInfos.parallelStream().filter(a -> !a.getShortName().contains("ST") && !a.getShortName().contains("退市") && !a.getZsz().contains("-")
                && !a.getCode().startsWith("8")).forEach(a -> {
            spriderController.hignLow(a.getCode(), a.getSecurityCodeType());
        });


        // 更新完成后 休息一秒
        try {
            TimeUnit.MILLISECONDS.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //状态更改
        List<LowHigh> lowHighs = lowHighDao.selectList(new LambdaQueryWrapper<>());
        lowHighs.parallelStream().forEach(a -> {
            StringBuffer str = new StringBuffer();
//
//            if (a.getName().equals("金地集团")){
//                System.out.println();
//            }
            String lowPoint = a.getLowPoint();
            String[] split = lowPoint.split(";");
            if (split.length < 2) {
                return;
            }
            String last = split[split.length - 1];
            String lastL = split[split.length - 2];
            String[] lastValue = last.split(",");
            String[] lastLValue = lastL.split(",");
            double v = Double.parseDouble(lastValue[1]);
            double kd = Double.parseDouble(lastValue[2]);
            double v1 = Double.parseDouble(lastLValue[1]);
            double kd2 = Double.parseDouble(lastLValue[2]);
            double lkd = kd;
            if (kd2 < kd) {
                lkd = kd - kd2;
            }
            if (v > v1) {
                str.append("2");
            }
            if (v == v1) {
                str.append("1");
            }
            if (v < v1) {
                str.append("0");
            }

            BigDecimal one = BigDecimal.valueOf(v);
            BigDecimal two = BigDecimal.valueOf(v1); //
            BigDecimal three = (one.subtract(two)).divide(two, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
            //

            String highPoint = a.getHighPoint();
            String[] splitH = highPoint.split(";");
            if (splitH.length < 2) {
                return;
            }
            String lastH = splitH[splitH.length - 1];
            String lastHL = splitH[splitH.length - 2];
            String[] lastHValue = lastH.split(",");
            String[] lastHLValue = lastHL.split(",");
            double vh = Double.parseDouble(lastHValue[1]);
            double vhkd = Double.parseDouble(lastHValue[2]);
            double vh2 = Double.parseDouble(lastHLValue[1]);
            double vhkd2 = Double.parseDouble(lastHLValue[2]);
            double hkd = vhkd;
            if (vhkd2 < vhkd) {
                hkd = vhkd - vhkd2;
            }
            if (vh > vh2) {
                str.append("2");
            }
            if (vh == vh2) {
                str.append("1");
            }
            if (vh < vh2) {
                str.append("0");
            }

            BigDecimal oneH = BigDecimal.valueOf(vh);
            BigDecimal twoH = BigDecimal.valueOf(vh2); //
            BigDecimal threeH = (oneH.subtract(twoH)).divide(twoH, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));

            lowHighDao.updateById(LowHigh.builder().code(a.getCode()).state(str.toString())
                    .zdfl(three.toString()).zdfh(threeH.toString())
                    .kdl(String.valueOf(lkd)).kdh(String.valueOf(hkd)).build());

        });

    }


}








